package com.nettm.leetcode;

import java.util.LinkedList;

public class AddTwoNumbers002 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(8);
        // l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(0);
        // l2.next = new ListNode(6);
        // l2.next.next = new ListNode(4);

        ListNode result = AddTwoNumbers002.addTwoNumbers(l1, l2);

        StringBuilder buf = new StringBuilder();
        while (result != null) {
            buf.append(result.val);
            buf.append(" -> ");
            result = result.next;
        }
        System.out.println(buf.toString().substring(0, buf.length() - 4));
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = null;
        LinkedList<Integer> tmp = new LinkedList<>();

        boolean iscarry = false;
        while (l1 != null || l2 != null) {

            int a = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0);
            a = iscarry ? ++a : a;
            if (a >= 10) {
                iscarry = true;
                tmp.add(a - 10);
            } else {
                iscarry = false;
                tmp.add(a);
            }
            l1 = l1 != null ? l1.next : l1;
            l2 = l2 != null ? l2.next : l2;
        }

        if (iscarry) {
            tmp.add(1);
        }

        ListNode tmpNode = null;
        while (tmp.size() > 0) {
            if (tmpNode == null) {
                tmpNode = new ListNode(tmp.pollLast());
            } else {
                result = new ListNode(tmp.pollLast());
                result.next = tmpNode;
                tmpNode = result;
            }
        }

        if (tmpNode != null && result == null) {
            result = tmpNode;
        }

        return result;
    }
}
